package com.jtcoding.chat.service.impl;

import com.jtcoding.chat.model.User;
import com.jtcoding.chat.service.MailService;
import com.jtcoding.chat.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.PostConstruct;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.LinkedBlockingQueue;

import static com.jtcoding.chat.service.UserService.USER_STATUS_PAT;

/**
 * @author jason.tang
 * @create 2019-02-12 14:17
 * @description
 */
@Slf4j
@Service("mailService")
public class MailServiceImpl implements MailService {

    private LinkedBlockingQueue<User> actQueue = null;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private UserService userService;

    @Value("${spring.mail.username}")
    private String from;

    @PostConstruct
    private void autoStartup() {
        actQueue = new LinkedBlockingQueue<>();

        this.startActivation();
    }


    private void startActivation() {
        new Thread(() -> {
            try {
                User user = null;
                while (null != (user = actQueue.take())) {
                    this.sendActivitiesMail(user.getLoginEmail(), user);
                }
            } catch (Exception e) {
                log.error("Send message {} failed.", e);
            }
        }).start();
    }


    @Override
    public void sendActivitiesMail(String sendTo, User user) throws MessagingException {
        //创建邮件正文
        Context context = new Context();
        //设置模板需要替换的参数
        context.setVariable("userNum", user.getUserNum());
        //使用 templateEngine 替换掉动态参数生产出最后的 HTML 内容
        String emailContent = templateEngine.process("activationMailTemplate", context);
        //最后调用 sendHtmlMail 发送邮件
        this.sendHtmlMail(sendTo,"激活邮件", emailContent);

        User tempUser = userService.getUserByNum(user.getUserNum());
        tempUser.setStatus(USER_STATUS_PAT);
        userService.modifyUserStatus(tempUser);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void putUser(User user) {
        try {
            actQueue.put(user);
        } catch (InterruptedException e) {
            log.error("putNTF", e);
        }
    }

    @Override
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        //true 表示需要创建一个 multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        mailSender.send(message);
    }

}